package com.google.gmeetings

class HomeController {

    def springSecurityService

    def index = {
        def currentUser = lookupUser()

        println("--------> Finding by owner")
        def myMeetings = Meeting.findAllByOwner(currentUser)
        println("--------> Finding invited meetings")
        def inviteMeetings = Meeting.withCriteria {
            participants {
                'in'('id', [currentUser.id])
            }
            or {
                isEmpty('userStatus')
                userStatus {
                    eq('status', StatusValue.DECLINED.value)
                    eq('user', currentUser)
                }
            }
        }

        println("--------> Finding going meetings")
        def goingMeetings = Meeting.withCriteria {
            participants {
                'in'('id', [currentUser.id])
            }

            userStatus {
                eq('status', StatusValue.ACCEPTED.value)
                eq('user', currentUser)
            }
        }
        [invitedMeetings: inviteMeetings, goingMeetings: goingMeetings, myMeetings: myMeetings]
    }


    private User lookupUser() {
        return User.get(springSecurityService.principal.id)
    }

    def acceptMeeting = {
        println("Accepting Meeting with id : $params.id")
        def meeting = Meeting.get(params.id)
        println("Meeting found : $meeting")
        def currentUser = lookupUser()
        println("User found : $currentUser")
        def joinStatus = JoinStatus.findByUserAndMeeting(currentUser, meeting) ?: new JoinStatus(meeting: meeting, user: currentUser)
        println("Join Status found : $joinStatus")
        joinStatus.setStatus(StatusValue.ACCEPTED.value)
        joinStatus.save(flush: true, failOnError: true)
        println("Join Status created : $joinStatus")
        println("*************************************")
        redirect(controller: 'home')
    }

    def declineMeeting = {
        println("Declining Meeting with id : $params.id")
        def meeting = Meeting.get(params.id)
        println("Meeting found : $meeting")
        def currentUser = lookupUser()
        println("User found : $currentUser")
        def joinStatus = JoinStatus.findByUserAndMeeting(currentUser, meeting) ?: new JoinStatus(meeting: meeting, user: currentUser)
        println("Join Status found : $joinStatus")
        joinStatus.setStatus(StatusValue.DECLINED.value)
        joinStatus.save(flush: true)
        println("*************************************")
        redirect(controller: 'home')
    }
}
